package app

import (
	"crow-spy/conf"
	"crow-spy/pkg"
	"errors"
	"fmt"
	"github.com/toolkits/pkg/logger"
	"io/ioutil"
	"strings"
)

type WordGroup struct {
	Word01 string
	Word02 string
}

var WordRepo []WordGroup

func init() {
	WordRepo = InitWordRepo()
}

// readWordsFile
// 从文件读取词汇表，按行输出
func readWordsFile() (lines []string) {
	// 词组表路径
	filePath := "./words.md"
	// 读取文件内容
	content, err := ioutil.ReadFile(filePath)
	if err != nil {
		fmt.Println("读取文件失败:", err)
		return
	}
	// 分割词汇表，每行一组词
	lines = strings.Split(string(content), "\n")
	return lines
}

// InitWordRepo
// 初始化词库，放入内存
func InitWordRepo() (wordRepo []WordGroup) {
	lines := readWordsFile()
	for _, line := range lines {
		var words WordGroup
		wordList := strings.Split(line, " ")
		words.Word01 = wordList[0]
		words.Word02 = strings.TrimSuffix(wordList[1], "\r")
		wordRepo = append(wordRepo, words)
	}
	return wordRepo
}

// distributeWord
// 给每个用户分配词
func distributeWord() (err error) {
	maxNum := len(WordRepo)
	if maxNum == 0 {
		err = errors.New("词库的词用完了")
		logger.Error(err)
		return err
	}
	//随机获取一个行号
	groupNumber := pkg.GenerateRandomInt(maxNum)
	usedGroup := WordRepo[groupNumber]
	//fmt.Printf("取到了第%d组，内容为%+v\n", groupNumber, usedGroup)
	// 创建人员列表
	userList := make([]string, conf.CrowConfig.TNumber)
	// 将好人词汇从前向后分配给用户
	for n := 0; n < int(conf.CrowConfig.UNumber); n++ {
		userList[n] = usedGroup.Word01
	}
	// 将卧底词汇从前往后分配给剩下的用户
	for n := int(conf.CrowConfig.UNumber); n < int(conf.CrowConfig.TNumber); n++ {
		userList[n] = usedGroup.Word02
	}
	//删除本次游戏使用的词
	WordRepo = deleteUsedGroup(groupNumber, WordRepo)
	// 打乱顺序，给用户重新分配
	pkg.RandomSort(userList)
	// 循环输出给每一个用户
	for n, word := range userList {
		fmt.Println("=======分词开始========")
		fmt.Printf("第%d个玩家，按回车看词", n+1)
		// 等待玩家输入
		fmt.Scanln()
		fmt.Printf("%c[%d;%d;%dm%s%c[0m", 0x1B, 0, 40, 32, word+"\n", 0x1B)
		fmt.Println("回车清除屏幕")
		// 等待玩家输入
		fmt.Scanln()
		//清空屏幕
		//fmt.Printf("\033[2J")
		pkg.CleanScreen()
	}
	return nil
}

// 从内存中删除已使用的词
func deleteUsedGroup(groupNumber int, sGroupList []WordGroup) (newGroupList []WordGroup) {
	newGroupList = make([]WordGroup, len(sGroupList)-1)
	// 将原始切片的索引从 0 到 index-1 的元素复制到新切片
	copy(newGroupList, sGroupList[:groupNumber])
	// 将原始切片的索引从 index+1 到末尾的元素复制到新切片
	copy(newGroupList[groupNumber:], sGroupList[groupNumber+1:])
	//fmt.Println(newGroupList)
	return newGroupList
}
